package array;

public class MyArrayList {
    private Object[] value;
    private int size;

    public MyArrayList(){
        //value = new Object[16];
        this(16);//this 指向下面的构造器
    }
    public MyArrayList(int size){
        if(size<0){
            try {
                throw new Exception();//手动抛一个异常
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        value = new Object[size];
    }

    public int getSize() {
        return size;
    }

    public void add(Object obj){
        value[size]=obj;
        size++;
        if(size>=value.length){
            //扩容
            int newCapacity = value.length*2;
            Object[] newList = new Object[newCapacity];
            //System.arraycopy();把老数组里的拷贝到新数组里

            for (int i=0;i<value.length;i++){
                newList[i]=value[i];
            }
            value = newList;
        }
    }

    public Object get(int index){
        if (index<0||index>size-1){//[0,size-1]
            try {
                throw new Exception();//手动抛一个异常
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return value[index];
    }

    public int indexOf(Object obj){
        if(obj==null){
            return -1;
        }else{
            for(int i=0;i<value.length;i++){
                if (obj==value[i]){
                    return i;
                }
            }
            return -1;
        }
    }

    public static void main(String[] args){
        MyArrayList list = new MyArrayList(2);
        list.add("aa");
        list.add(new Human("张哲"));
        list.add("bb");

        //
       Human h = (Human) list.get(1);
       System.out.println(h.getName());
        System.out.println(list.getSize());
    }
}
